import { useCallback, useContext, useRef } from 'react';
import { BaseHelp, HelpContext, Table, TableSelectionModel } from '../../../functionalComponent';
import { Layout, iup, useRefCallback } from '../../../util';
import { findFilterIndexes } from './utils';

const tableProps: any = {
  rowSelected: false,
  rowChecked: true,
  cache: false,
  headerMenu: false,
  style: { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 }
};
const tableStyle: any = { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 };
const { Header, Footer, MultipleButtons } = BaseHelp;

/**
 * 核算项目帮助-简单版
 * @returns
 */
export function HelpContentSimple() {
  const {
    request,
    ok,
    contentParams: { getFieldValue, columns, helpTitle, helpId, selectedArray, multiple, footer },
    randomKey
  } = useContext<any>(HelpContext);
  const btnRef = useRef<any>();

  const rightTable = useRef<any>();

  const SUB_TABLE_KEY = `${helpId}_${randomKey}_sub`;

  // 表格
  const getTable = useCallback((tableKey) => tableKey && iup.compIns[tableKey].getApi(), []);

  const getResult: any = () => {
    if (multiple) {
      const result = rightTable.current
        .getApi()
        .getRows()
        .map((r) => ({
          value: getFieldValue(r),
          label: getFieldValue(r, 'label'),
          origin: { ...r }
        }));
      return result.length > 0 ? result : undefined;
    } else {
      const value = getTable(SUB_TABLE_KEY).getSelectedData()[0];
      if (value) {
        return { value: getFieldValue(value), label: getFieldValue(value, 'label'), origin: { ...value } };
      }
      return undefined;
    }
  };

  const toRight = (values: any) => {
    if (multiple) {
      btnRef.current.toRight(values);
    } else {
      ok(getResult());
    }
  };

  // 默认选中
  const onDataLoad = useRefCallback((table) => {
    const { dataSource = [] } = table.getState() || {};
    const selectIndex = findFilterIndexes(dataSource, (it) => (selectedArray || []).map((x) => x.id).includes(it.id));
    table.setSelected(selectIndex);
  });

  return (
    <Layout>
      <Header title={helpTitle || '核算项目帮助'} />
      <Layout.Flex direction="row" style={{ padding: 5 }}>
        <Layout.Flex direction="column">
          <Table
            style={tableStyle}
            id={SUB_TABLE_KEY}
            columns={columns}
            pagination={{ hideOnSinglePage: false }}
            autoLoad={true}
            request={request}
            response={(res) => ({ total: res.total ?? 0, record: res.list || [] })}
            onDataLoad={onDataLoad}
            rowSelection={{
              type: multiple
                ? [TableSelectionModel.CHECKBOX, TableSelectionModel.MULTIPLE_INTERVAL]
                : TableSelectionModel.ROW
            }}
            onRow={(rowIndex, table) => ({
              onDoubleClick: () => toRight([table.getRow(rowIndex)])
            })}
          />
        </Layout.Flex>
        {multiple && (
          <MultipleButtons
            getRowKey={getFieldValue}
            outRef={btnRef}
            getActiveTable={() => getTable(SUB_TABLE_KEY)}
            getResultTable={() => rightTable.current.getApi()}
          />
        )}
        {multiple && (
          <Layout.Slider size={200}>
            <Table
              {...tableProps}
              columns={columns}
              dataSource={selectedArray}
              ref={rightTable}
              onRow={(rowIndex) => ({
                onDoubleClick: () => btnRef.current.toLeft(rowIndex)
              })}
            />
          </Layout.Slider>
        )}
      </Layout.Flex>
      <Footer getResult={getResult}>{footer && <span style={{ flex: 1, width: 0 }} children={footer} />}</Footer>
    </Layout>
  );
}
